package jjn.round2;

import commons.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author Jiang Jining
 * @since 2023-05-03 19:25
 */
public class Offer32_1_LevelOrder {
    public int[] levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> result = new ArrayList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode poll = queue.poll();
            if (poll != null) {
                result.add(poll.val);
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
        }
        int[] orderedResult = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            orderedResult[i] = result.get(i);
        }
        return orderedResult;
    }
}
